//
//  LBShareStartViewController.m
//  share
//
//  Created by 杨庆人 on 17/4/10.
//  Copyright © 2017年 杨庆人. All rights reserved.
//

#import "LBShareViewController.h"
#import <LBLoadingView/LBLoadingView.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <Masonry/Masonry.h>

#import "LBShareKeyModel+setKeyModel.h"
#import "LBShareCell.h"
#import "LBShareHeadLabel.h"
#import "LBShareCancelBtn.h"

#define Rows_number 4
#define LBShareItemSize_width (self.view.bounds.size.width - 3)/4.0
#define LBShareItemSize_height 100
#define LBShareHead_height 50

static LBShareViewController *shareView = nil;

@interface LBShareViewController ()

@property (nonatomic,strong)LBShareKeyModel * shareKeyModel;

@property (nonatomic,strong)UICollectionView * collectionView;

@property (nonatomic,copy)LBShareResultBlock shareResultBlock;

@property (nonatomic,strong)UIImageView * imageView;

@property (nonatomic,strong)LBChannelKeyModel * channelKeyModel;

@property (nonatomic,assign)CGFloat collection_height;

@property (nonatomic,strong)MASConstraint * masConstraint;

@end

@implementation LBShareViewController


-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
        layout.minimumInteritemSpacing = 0.5;
        layout.minimumLineSpacing = 0.5;
        [layout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.itemSize = CGSizeMake(LBShareItemSize_width, LBShareItemSize_height);
        layout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, LBShareHead_height);
        layout.footerReferenceSize = CGSizeMake(self.view.bounds.size.width, LBShareHead_height);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        [_collectionView setDelegate:(id<UICollectionViewDelegate> _Nullable)self];
        [_collectionView setDataSource:(id<UICollectionViewDataSource> _Nullable)self];
        [_collectionView setBackgroundColor:[UIColor whiteColor]];
        [_collectionView registerClass:[LBShareCell class] forCellWithReuseIdentifier:@"LBShareCell"];
        [_collectionView registerClass:[LBShareHeadLabel class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LBShareHeadLabel"];
        [_collectionView registerClass:[LBShareCancelBtn class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LBShareCancelBtn"];
        
        _collectionView.bounces = NO;
    }
    return _collectionView;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
    }
    return _imageView;
}

- (LBShareKeyModel *)shareKeyModel {
    if (!_shareKeyModel) {
        _shareKeyModel = [[LBShareKeyModel alloc] init];
    }
    return _shareKeyModel;
}
- (LBChannelKeyModel *)channelKeyModel {
    if (!_channelKeyModel) {
        _channelKeyModel = [[LBChannelKeyModel alloc] init];
    }
    return _channelKeyModel;
}

- (void)loadView{
    [super loadView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    
    [self.view addSubview:self.collectionView];
    
    self.collection_height  = ((shareView.shareKeyModel.channelArray.count / Rows_number) + 1) * LBShareItemSize_height + LBShareHead_height + LBShareHead_height + 1;
    
    __weak typeof(self)weakSelf = self;
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(weakSelf.view);
        weakSelf.masConstraint =  make.bottom.mas_equalTo(weakSelf.view.mas_bottom).offset(weakSelf.collection_height);
        make.height.mas_equalTo(weakSelf.collection_height);
    }];
    
    [self.collectionView reloadData];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.class dismiss];
}


- (void)setUmSocialAndChannelKeyWithChannelKeyBlock:(LBChannelKeyBlock)shareKeyModel {
    
    !shareKeyModel? :shareKeyModel(self.channelKeyModel);
    
    self.shareKeyModel = [LBShareKeyModel setKeyModelWithChannelKeyModel:self.channelKeyModel];
    
    // 设置友盟appkey
    
    NSAssert(self.shareKeyModel.UMSocialKey, @"友盟UMSocialKey不能为空！");
    
    [[UMSocialManager defaultManager] setUmSocialAppkey:self.shareKeyModel.UMSocialKey];
    
    /** 设置各个渠道的appKey、appSecret和redirectURL */
    for (LBChannelModel * model in self.shareKeyModel.channelArray) {
        
        if (model.appKey && model.appSecret && model.redirectURL) {
            [[UMSocialManager defaultManager] setPlaform:model.platformType appKey:model.appKey appSecret:model.appSecret redirectURL:model.redirectURL];
        }
    }
}

+ (void)modifyUmSocialChannelWithShareKeyModel:(void(^)(LBShareKeyModel * shareKeyModel))shareKeyBlock {
    
    [shareView.shareKeyModel cleanUnKnowData];
    
    !shareKeyBlock ? :shareKeyBlock(shareView.shareKeyModel);
    
    /** 设置各个渠道的appKey、appSecret和redirectURL */
    for (LBChannelModel * model in shareView.shareKeyModel.channelArray) {
        
        if (model.appKey && model.appSecret && model.redirectURL) {
            
            [[UMSocialManager defaultManager] setPlaform:model.platformType appKey:model.appKey appSecret:model.appSecret redirectURL:model.redirectURL];
        }
    }
}


+ (void)dismiss{
    
    [shareView.shareKeyModel cleanUnKnowData];
    
    shareView.masConstraint.offset = ((shareView.shareKeyModel.channelArray.count / Rows_number) + 1) * LBShareItemSize_height + LBShareHead_height + LBShareHead_height + 1;
    
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:1 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        [shareView.view layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        
        if (finished) {
            
            [UIView animateWithDuration:0.2 animations:^{
                
                shareView.view.alpha = 0.1f;
                
            } completion:^(BOOL finished) {
                
                [shareView removeFromParentViewController];
                
                [shareView.view removeFromSuperview];
            }];
            
        }
    }];
}


+ (void)setLBChannelKeyBlock:(LBChannelKeyBlock)shareKeyModel {
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        shareView = [[LBShareViewController alloc]init];
        
        [shareView setUmSocialAndChannelKeyWithChannelKeyBlock:shareKeyModel];
    });
}


+ (void)showWithShareTitle:(NSString *)shareTitle
             shareSubTitle:(NSString *)shareSubTitle
                  shareURL:(NSString *)shareURL
                shareImage:(UIImage *)shareImage
             shareImageUrl:(NSString *)shareImageUrl
          shareResultBlock:(LBShareResultBlock)shareResult {
    
    shareView.shareResultBlock = shareResult;
    
    /** 大标题 */
    shareView.shareKeyModel.shareTitle = shareTitle;
    /** 小标题 */
    shareView.shareKeyModel.shareSubTitle = shareSubTitle;
    /** 分享的web链接 */
    shareView.shareKeyModel.shareURL = shareURL;
    
    /** 标题图片，image或者imageUrl */
    if (shareImage) {
        shareView.shareKeyModel.shareImage = shareImage;
    }
    else if (shareImageUrl.length) {
        
        [LBLoadingView showInView:shareView.view];
        
        [shareView.imageView sd_setImageWithURL:[NSURL URLWithString:shareImageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            [LBLoadingView dismiss];
            
            shareView.shareKeyModel.shareImage = image;
        }];
    }

    [self.class show];
}


+ (void)show {
    
    [[[UIApplication sharedApplication].delegate window].rootViewController addChildViewController:shareView];
    [[[UIApplication sharedApplication].delegate window].rootViewController.view addSubview:shareView.view];
    // 修改数据源后必须刷新
    [shareView.collectionView reloadData];
    
    shareView.view.alpha = 0.1f;
    
    [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:10 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        shareView.view.alpha = 1.f;
        
    } completion:^(BOOL finished) {
        
        if (finished) {
            
            shareView.masConstraint.offset = 0;
            
            [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:1 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                
                [shareView.view layoutIfNeeded];
                
            } completion:nil];
        }
        
    }];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.shareKeyModel.channelArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * identifier = @"LBShareCell";
    
    LBShareCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    [cell setCellWithShareItemModel:self.shareKeyModel.channelArray[indexPath.row]];
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    LBChannelModel * model = self.shareKeyModel.channelArray[indexPath.row];
    
    if (model.platformType != UMSocialPlatformType_UnKnown) {
        [self.class shareWithSocialPlatformType:model.platformType currentViewController:self shareResultBlock:self.shareResultBlock];
        
        [self.class dismiss];
    }
    else {
        !self.shareResultBlock ? :self.shareResultBlock(model,LBShareNoHandling);
        
        [self.class dismiss];
    }
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        LBShareHeadLabel * label = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LBShareHeadLabel" forIndexPath:indexPath];
        
        return label;
    }
    else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        
        LBShareCancelBtn * button = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LBShareCancelBtn" forIndexPath:indexPath];
        
        __weak typeof(self)weakSelf = self;
        button.clickBlock = ^{
            [weakSelf.class dismiss];
        };
        
        return button;
    }
    return nil;
}



+ (void)startShareWithShareTitle:(NSString *)shareTitle
                   shareSubTitle:(NSString *)shareSubTitle
                        shareURL:(NSString *)shareURL
                      shareImage:(UIImage *)shareImage
                   shareImageUrl:(NSString *)shareImageUrl
           currentViewController:(id)currentViewController
              socialPlatformType:(UMSocialPlatformType)socialPlatformType
                shareResultBlock:(LBShareResultBlock)shareResult {
    
    /** 大标题 */
    shareView.shareKeyModel.shareTitle = shareTitle;
    /** 小标题 */
    shareView.shareKeyModel.shareSubTitle = shareSubTitle;
    /** 分享的web链接 */
    shareView.shareKeyModel.shareURL = shareURL;
    
    /** 标题图片，image或者imageUrl */
    if (shareImage) {
        shareView.shareKeyModel.shareImage = shareImage;
        
        [self.class shareWithSocialPlatformType:socialPlatformType currentViewController:currentViewController shareResultBlock:shareResult];
    }
    else if (shareImageUrl.length) {
        
        [LBLoadingView showInView:shareView.view];
        
        [shareView.imageView sd_setImageWithURL:[NSURL URLWithString:shareImageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            [LBLoadingView dismiss];
            
            shareView.shareKeyModel.shareImage = image;
            
            [self.class shareWithSocialPlatformType:socialPlatformType currentViewController:currentViewController shareResultBlock:shareResult];
        }];
    }
    else {
        
        [self.class shareWithSocialPlatformType:socialPlatformType currentViewController:currentViewController shareResultBlock:shareResult];
    }
}

+ (void)shareWithSocialPlatformType:(UMSocialPlatformType)socialPlatformType
              currentViewController:(id)currentViewController
                   shareResultBlock:(LBShareResultBlock)shareResult {
    
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    UMShareWebpageObject *shareWebObject = [UMShareWebpageObject shareObjectWithTitle:shareView.shareKeyModel.shareTitle descr:shareView.shareKeyModel.shareSubTitle thumImage:shareView.shareKeyModel.shareImage ? shareView.shareKeyModel.shareImage:[UIImage imageNamed:@"LBShareLogo"]];
    
    shareWebObject.webpageUrl = shareView.shareKeyModel.shareURL;
    
    shareWebObject.title = shareView.shareKeyModel.shareTitle;
    
    messageObject.shareObject = shareWebObject;
    
    messageObject.text = shareView.shareKeyModel.shareSubTitle;
    
    LBChannelModel * model = [[LBChannelModel alloc] init];
    
    model.platformType = socialPlatformType;
    
    NSLog(@"shareView.shareKeyModel.shareURL = %@",shareView.shareKeyModel.shareURL);
    
    __weak typeof(self)weakSelf = self;
    [[UMSocialManager defaultManager] shareToPlatform:socialPlatformType messageObject:messageObject currentViewController:currentViewController completion:^(id data, NSError *error) {
        if (!error) {
            
            !shareResult ? :shareResult(model,LBShareSuccessCode);
            NSLog(@"分享成功");
        }
        else{
            
            if (UMSocialPlatformErrorType_Cancel == error.code) {
                
                !shareResult ? :shareResult(model,LBShareCancelCode);
                NSLog(@"取消");
            }
            else {
                
                !shareResult ? :shareResult(model,LBShareFailureCode);
                NSLog(@"分享失败");
            }
        }
    }];
}


@end
